import {Http, RequestOptionsArgs, Headers, Response} from "@angular/http";
import {ReadableMessage} from "./domains";

import {Injectable, Inject} from "@angular/core";
import {HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse} from '@angular/common/http';
/**
 * Created by Administrator on 2017/4/28.
 */
@Injectable()
export class HttpHelper{
    contentHeaderEnum={
        formHeader:"application/x-www-form-urlencoded",
        jsonHeader:"application/json",
        textHeader:"text/plain"
    };
    constructor(@Inject("apiUrl")public apiUrl:string,private http:HttpClient){
        /*http.get("config.html")
        http.get("config.html")
            .toPromise()
            .then(res=>{

            },err=>{

            })*/
    }
    // apiUrl:String="http://192.168.0.200:9092";
    //apiUrl:String;
    authorization:string;
  /**
   * 为http请求生成请求参数的工具函数
   * @param contentType http请求提供的内容类型
   * @param accept http请求接受的内容类型
   * @returns {{headers: Headers}}
   */
    getHttpHeaders(contentType: string = "application/json",accept?:string): HttpHeaders {
        let hs = new HttpHeaders({
            "Content-Type":contentType
        });
        if(this.authorization) hs=hs.append("Authorization",this.authorization)
        return accept?hs.append("Accept",accept):hs;
    }

    /**
     * @deprecated
     * @param {string} contentType
     * @param {string} accept
     * @returns {{headers: HttpHeaders; observe: "response"}}
     */
    getHttpOption(contentType?: string ,accept?: string): {headers:HttpHeaders,observe:"response"} {
        let httpHeaders = new HttpHeaders();
        if (contentType) {
            httpHeaders.append("Content-Type",contentType);
        }
        if (accept) {
            httpHeaders.append("Accept",accept);
        }
        httpHeaders.append("Authorization",this.authorization);
        let httpOption:{headers:HttpHeaders,observe:"response"} = {
            headers: httpHeaders,
            observe: "response"
        };
        return httpOption;
    }

    getJson<T>(url:string):Promise<T>{
        let header:HttpHeaders=this.getHttpHeaders(undefined,"application/json");
        return this.http.get<T>(this.apiUrl+url,{headers:header,observe:"response"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    getText(url:string):Promise<string>{
        let header:HttpHeaders=this.getHttpHeaders(undefined,"text/plain");
        return this.http.get(this.apiUrl+url,
            {headers:header,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    getBoolean(url:string):Promise<boolean>{
        let header:HttpHeaders=this.getHttpHeaders(undefined,"text/plain");
        return this.http.get(this.apiUrl+url,
            {headers:header,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>/true/.test(res.body))
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    postToJson<T>(url:string,body:any,contentType:string="application/json"):Promise<T>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"application/json");
        return this.http.post<T>(this.apiUrl+url,body,{headers:headers,observe:"response"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    postToText(url:string,body:any,contentType:string="application/json"):Promise<string>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"text/plain");
        return this.http.post(this.apiUrl+url,body,{headers:headers,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    postToBoolean(url:string,body:any,contentType:string="application/json"):Promise<boolean>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"text/plain");
        return this.http.post(this.apiUrl+url,body,{headers:headers,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>/true/.test(res.body))
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    putToJson<T>(url:string,body:any,contentType:string="application/json"):Promise<T>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"application/json");
        return this.http.put<T>(this.apiUrl+url,body,{headers:headers,observe:"response"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    putToText(url:string,body:any,contentType:string="application/json"):Promise<string>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"text/plain");
        return this.http.put(this.apiUrl+url,body,{headers:headers,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>res.body)
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    putToBoolean(url:string,body:any,contentType:string="application/json"):Promise<boolean>{
        let headers:HttpHeaders=this.getHttpHeaders(contentType,"text/plain");
        return this.http.put(this.apiUrl+url,body,{headers:headers,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>/true/.test(res.body))
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    delete(url:string):Promise<boolean>{
        let headers:HttpHeaders=this.getHttpHeaders(undefined,"text/plain");
        return this.http.delete(this.apiUrl+url,{headers:headers,observe:"response",responseType:"text"})
            .toPromise()
            .then(res=>/true/.test(res.body))
            .catch(err=>Promise.reject(this.parseError(err)));
    }
    /**
    * 解析http错误回应的工具函数
    * @param errRes http请求返回的错误回应
    * @returns ReadableMessage
    */
    parseError(errRes:HttpErrorResponse):ReadableMessage{
      switch(errRes.status){
          case 200:
              return new ReadableMessage("网络错误或服务器无法响应",true);
          case 488:
          case 444:
              return JSON.parse(errRes.error);
          case 404:
              return new ReadableMessage("请求的页面不存在",false);
          default:
              return new ReadableMessage(`未知的http请求错误${errRes.status}`,true,errRes.error);
      }
    }
}
